package main

import (
	"context"
	"fmt"
	"gin-blog/databases/mysql"
	"gin-blog/router"
	"gin-blog/utils/gredis"
	"gin-blog/utils/logging"
	"gin-blog/utils/setting"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"
)

func init()  {
	setting.Setup()
	mysql.Setup()
	gredis.Setup()
	logging.Setup()
}

func main() {
	router := router.InitRouter()

	s := &http.Server{
		Addr:           fmt.Sprintf(":%d", setting.ServerSetting.HttpPort),
		Handler:        router,
		ReadTimeout:    setting.ServerSetting.ReadTimeout,
		WriteTimeout:   setting.ServerSetting.WriteTimeout,
		MaxHeaderBytes: 1 << 20,
	}

	go func() {
		if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()
	// 优雅Shutdown（或重启）服务
	// 1秒后优雅Shutdown服务
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt) //syscall.SIGKILL
	<-quit
	log.Println("Shutdown Server ...")
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
	defer cancel()
	if err := s.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
	select {
		case <-ctx.Done():
	}
	log.Println("Server exiting")
}
